// ActionScript file
import com.roguedevelopment.objecthandles.ObjectHandles;
import com.roguedevelopment.objecthandles.SpriteHandle;

import flash.events.Event;
import flash.events.MouseEvent;

import mx.collections.ArrayCollection;
import mx.containers.Canvas;
import mx.controls.Alert;
import mx.controls.Image;
import mx.core.DragSource;
import mx.effects.Zoom;
import mx.events.DragEvent;
import mx.events.ListEvent;
import mx.events.SliderEvent;
import mx.managers.DragManager;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;


private var site_:String= '';
private var sitenme:String = '';
private var picid:Number = 0;

public var zoom:Zoom = new Zoom();
public var ob:ObjectHandles;

[Bindable] private var URLConfigRPC:String = 'getconfig.php';
[Bindable] private var PhotosRPC:String = 'getphotos.php';
[Bindable] private var GoodsRPC:String = 'getgoods.php';
[Bindable] private var SaveHotAreaRPC:String = 'savehotarea.php';
[Bindable] private var GetHotAreaRPC:String = 'gethotarea.php';
[Bindable] private var Photos:ArrayCollection = new ArrayCollection(); // 上传的所有图片
//[Bindable] private var xmlphotos:XMLListCollection = new XMLListCollection();
//[Bindable] private var goods:ArrayCollection = new ArrayCollection();
[Bindable] private var goods:Array = new Array();


public var myloading:loading = new loading();
private var myloadflag:Number = 1;
private var selectedobj:String;


//初始设置
public function init():void{
	this.SendHttpService(this.URLConfigRPC, null, this.getConfigRPCResult, '加载配置信息');
	myloading.mylbild();
	//addChild(this.myloading);
	
	
}

//createComplete
public function com():void{
	hota.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
	mainid.addEventListener(DragEvent.DRAG_ENTER,dragEnterHandler);
    mainid.addEventListener(DragEvent.DRAG_DROP,dragDropHandler);
    ob = new ObjectHandles(mainid , null, new ClassFactory(SpriteHandle)); //添加objecthandle
    zoom.target = mainid;
    
}


//callback
private function getConfigRPCResult(event:ResultEvent):void
{
	//trace(event.result);
	var config:XML = XML(event.result);
	this.site_ = config.siteurl;
	
	//读取商品
	this.SendHttpService(this.GoodsRPC, null, this.getGoodsRPCResult, '加载商品列表');
}
//callback
private function getPhotosRPCResult(event:ResultEvent):void{
	//trace(event.result);
	var tmp:Array = new Array();
	Photos.removeAll();
	for each (var s:XML in event.result.info){
		Photos.addItem({
						img_id:s.img_id, 
						goods_id:s.goods_id, 
						img_url:s.img_url, 
						img_desc:s.img_desc,
						thumb_url:s.thumb_url, 
						img_original:s.img_original, 
						width:s.width, 
						height:s.height
					});
		//trace(s.img_id);
	}
	
	trace('照片加载完毕');
}

//callback
private function getGoodsRPCResult(event:ResultEvent):void{
	//trace(event.result);
	//Alert.show(event.result.toString());
	var tmp:Array = new Array();
	//Photos.removeAll();
	var tmp1:Array = new Array();
	for each (var s:XML in event.result.info){
		goods.push({id:s.goods_id.toString(), name:s.goods_sn.toString(), label:s.goods_name.toString()});
		//trace(s.goods_name);
	}
	
	trace('商品加载完毕');
}

// gleft
private function _gleft(delta:int = 10):void{
	if(photolist.horizontalScrollPosition < photolist.maxHorizontalScrollPosition){
		photolist.horizontalScrollPosition += 1;
	}
}

// gright
private function _gright(delta:int = 10):void{
	if(photolist.horizontalScrollPosition > 0){
		photolist.horizontalScrollPosition -= 1;
	}
}

//upbtn
private function scrollUp(delta:int = 1):void {
	if(container.verticalScrollPosition > 0){
		//container.verticalScrollPosition -= delta;
	}
	if(goods_list.verticalScrollPosition > 0){
		goods_list.verticalScrollPosition -= delta;
	}
}
            
//downbtn
private function scrollDown(delta:int = 1):void {
	if(container.verticalScrollPosition < container.maxVerticalScrollPosition){
		//container.verticalScrollPosition += delta;
	}
	if(goods_list.verticalScrollPosition < goods_list.maxVerticalScrollPosition){
		goods_list.verticalScrollPosition += delta;
	}
}


//显示商品图片列表
private function showphoto(e:Event):void{
	//trace(e.currentTarget.selectedItem.id.toString() + e.currentTarget.selectedItem.name.toString());
	//读取图片
	this.SendHttpService(this.PhotosRPC, {pid:e.currentTarget.selectedItem.id}, this.getPhotosRPCResult, '加载商品相册列表');
}

private function onMouseWheel(event:MouseEvent):void {
	if(event.delta > 0){
		scrollUp(3);
 	}else if(event.delta < 0){
    	scrollDown(3);
 	}
}

//在画布里载入图片
private function showphoto1(e:ListEvent):void{
	//显示loading
	maincav.addChild(this.myloading);
	this.myloadflag = 1;//显示时flag为1。
	//删除所有子元素
	ob.selectionManager.clearSelection();
	mainid.removeAllChildren();
	//添加内容
	var value:Object = e.itemRenderer.data;
	var img:Image = new Image();
	img.source = value.img_original;
	img.percentWidth = 100;
	img.percentHeight = 100;
	mainid.width = value.width;
	mainid.height = value.height;
	//trace(maincav.width);
	//trace(maincav.height);
	var zratio:Number = 1; //缩放值，默认为100%。
	var xw:Number = maincav.width/value.width;//trace('xw'+xw);
	var xh:Number = maincav.height/value.height;//trace('xh'+xh);
	if( value.width > maincav.width ){
		//宽超出范围
		zratio = xw;
	}else if(value.height>maincav.height){
		// 未超出，不缩放，以原始大小显示。
		zratio = xh;
	}
	//trace(zratio);
	var zt:Number = Math.floor(zratio*100);
	//trace(zt);
	this.picid = value.img_id;
	mainid.addChild(img);
	mainid.setChildIndex(img, 0);
	//this.myloading.percentWidth = 100;
	//this.myloading.percentHeight = 100;
	//Alert.show(this.picid.toString());
	setHotArea(this.picid);//回填相框
	
	zoom.zoomHeightTo = zt/100;
	zoom.zoomWidthTo = zt/100;
	hs1.value = zt;
	zoom.play();
	
}

//hota 的鼠标按下事件
private static function mouseDownHandler(event:MouseEvent):void{  
	//Alert.show(event.currentTarget.toString());
	var dragInitiator:Image = Image(event.currentTarget);
    var ds:DragSource = new DragSource();
    ds.addData(dragInitiator, "myRule");
    DragManager.doDrag(dragInitiator, ds, event);
}

// mainid的dragEnter事件
private static function dragEnterHandler(event:DragEvent):void {
	if (event.dragSource.hasFormat("myRule")){
    	DragManager.acceptDragDrop(Canvas(event.currentTarget));
    }
}

      
//drop事件
private  function dragDropHandler(event:DragEvent):void {
	var dragObject:Image = Image(event.dragInitiator);
    if(dragObject.parent!=event.currentTarget){
    	var newhot:hoterea = new hoterea();
    	newhot.x = Canvas(event.currentTarget).mouseX;
    	newhot.y = Canvas(event.currentTarget).mouseY;
    	newhot.name = 'hota'+mainid.numChildren;
    	application.ob.registerComponent(newhot, newhot);
    	Canvas(event.currentTarget).addChild(newhot);
    }
}

//


//application的鼠标按下事件
private function appclick(event:Event):void{  
	this.setFocus();
	//如果点击canvas，则取消元素的被选中焦点。
	if(event.target == this ){
		ob.selectionManager.clearSelection();
	}
	
	//得到元素的name,即当前被选中的元素。
	var tmp:Object = event.target;
	trace(event.target.toString());
	if(tmp is hoterea){
		this.selectedobj = (tmp as hoterea).name;
		trace(this.selectedobj);
	}else{
		this.selectedobj = '';
	}
	
}
// maincav click
private function maincavclick(event:Event):void{
	trace(event.currentTarget);
	Alert.show(event.currentTarget.toString());
}
// mainid click
private function mainidclick(event:Event):void{
	trace(event.currentTarget);
	//Alert.show(this.toString());
	this.setFocus();
	if(event.currentTarget is Canvas){
		//ob.selectionManager.clearSelection();
	}
}

//hoterea的单击事件
private function hotereaClick(event:Event):void{
	//Alert.show(event.target.parent);
	if(event.target.parent is Canvas){
		//ob.selectionManager.clearSelection();
	}	
}

private function parentIsThis(o:DisplayObject):Boolean{
	if (o.parent != null){
		if(o.parent is hoterea){
        	return true;
  		}else{
            return parentIsThis(o.parent);
  		}
  	}else{
		return false;
  	}
}
private function handler(event:MouseEvent):void{
	if (!parentIsThis(event.target as DisplayObject)){
    	mainid.setFocus();
 	}
}
//zoom的change事件            
private function zoom1(event:SliderEvent):void{
	var val:Number = hs1.value/100;
	zoom.zoomHeightTo = val;
	zoom.zoomWidthTo = val;
	zoom.play();
}            
          
//保存热区
private function savehot():void{
	var info:String = '';
	for(var i:Number=0;i<mainid.numChildren;i++ ){
		if(mainid.getChildAt(i) is hoterea){
			var obj:Object = mainid.getChildAt(i);
			var hotobj:hoterea = obj as hoterea;
			info += "<info><idx>"+i+"</idx><x>"+hotobj.x+"</x><y>"+hotobj.y+"</y><width>"+hotobj.width+"</width><height>"+hotobj.height+"</height><rotate>"+hotobj.rotation+"</rotate></info>";
		}
	}
	var hotxml:String = "<hoterea>"+info+"</hoterea>"
	//trace(hotxml);
	//trace(this.picid);
	//保存
	this.SendHttpService(this.SaveHotAreaRPC, {pid:this.picid,hotarea:hotxml}, this.SaveHotAreaRPCResult, '保存热区');
}
//callback
private function SaveHotAreaRPCResult(event:ResultEvent):void{
	//trace(event.result);
	if(event.result == 1){
		Alert.show('保存完毕！','信息');
	}else{
		Alert.show( '保存失败','错误');
	}
	
	
	trace('热区保存完毕');
}      
          
//取回hotarea数据并回填
private function setHotArea(value:Number):void{
	this.SendHttpService(this.GetHotAreaRPC, {pid:value}, this.GetHotAreaRPCResult, '加载热区');
}        
//callback
private function GetHotAreaRPCResult(event:ResultEvent):void{
	//trace(event.result);
	//Alert.show(event.result.toString());
	if(event.result != '0' && event.result!='' && event.result!='<hotarea></hotarea>'){
		for each(var s:XML in event.result.info){
			var ha1:hoterea = new hoterea();
			ha1.width = s.width;
			ha1.height = s.height;
			if(s.rotate!='' && s.rotate!=0){
				ha1.rotation = s.rotate;
			}
			ha1.x = s.x;
			ha1.y = s.y;
			application.ob.registerComponent(ha1, ha1);
			mainid.addChild(ha1);
		}
	}
	//添加热区完成，flag减1，为0时去除loading显示
	this.myloadflag -= 1;
	if(this.myloadflag == 0){
		maincav.removeChild(this.myloading);
	}
}  
            
//删除选中的热区
private function delhotarea():void{
	if(this.selectedobj != ''){
		mainid.removeChild(mainid.getChildByName(this.selectedobj));
		this.selectedobj  = '';
		ob.selectionManager.clearSelection();
	}else{
		Alert.show("请选择一个相框。","信息");
	}
	
}       




//*******************************************************************************//

/**
 * 发送HTTPService 
 * @param String url
 * @param Object param
 * @param Function Callback
 * 
 */
public function SendHttpService( url:String, param:Object = null, Callback:Function = null, name:String='' ):void
{
	var httpServiceObj:HTTPService = new HTTPService();
	httpServiceObj.resultFormat = "e4x";
	httpServiceObj.method = "POST";
	httpServiceObj.url = url;
	httpServiceObj.addEventListener(FaultEvent.FAULT, function(event:FaultEvent):void{doFault(event,name)} );
	httpServiceObj.addEventListener(ResultEvent.RESULT, Callback );
	httpServiceObj.send(param);
}

/**
 *  do fault for HTTPService
 */
private function doFault(event:FaultEvent, name:String):void{
	trace(name+' is Fault.');
	trace(event.message);
	Alert.show(event.message.toString());
	Alert.show(name+'失败.');
	//event.target.sent();
	//this.process1.label = name+'加载失败。 '+this.countForLoad;
}
